#region Copyright
//	Copyright (c) 2007 eBay, Inc.
//
//	This program is licensed under the terms of the eBay Common Development and 
//	Distribution License (CDDL) Version 1.0 (the "License") and any subsequent 
//	version thereof released by eBay.  The then-current version of the License 
//	can be found at https://www.codebase.ebay.com/Licenses.html and in the 
//	eBaySDKLicense file that is under the eBay SDK install directory.
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using MultiThread;

namespace GetItemTester
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        #region control fields

        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.Button btnStop;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.TextBox txtLogger;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        #endregion
        private Button button1;
        private FolderBrowserDialog folderBrowserDialog1;

        private IList<KeyValuePair<string, string>> listingImages = new List<KeyValuePair<string, string>>();
        private IList<string> productCodes = new List<string>();
        IDictionary<string, ImageItem> generatedListingImages = new Dictionary<string, ImageItem>();
        private TextBox textBox1;
        private Button btnBrowse;
        private Button button2;
        #region private fields

        private ItemFetcher fetcher;

        #endregion

        #region private properties

        /// <summary>
        /// specify how many threads will be tested
        /// </summary>
        private int NumThreads
        {
            get { return Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings.Get("numOfTreads")); ; }
        }

        private bool IsRampUp
        {
            get { return Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("IsRampUp")); ; }
        }
        /// <summary>
        /// 
        /// </summary>
        private int NumCalls
        {
            get { return listingImages.Count; }
        }

        /// <summary>
        /// specify eBay Token
        /// </summary>
        public string eBayToken
        {
            get { return System.Configuration.ConfigurationManager.AppSettings.Get("UserAccount.ApiToken").Trim(); }
            set { ConfigurationManager.AppSettings["UserAccount.ApiToken"] = value; }
        }

        public string eBayUser
        {
            get { return System.Configuration.ConfigurationManager.AppSettings.Get("eBayUser").Trim(); }
            set
            {
                ConfigurationManager.AppSettings["eBayUser"] = value;

            }
        }
        public string DefaultPhotoFolder
        {
            get { return System.Configuration.ConfigurationManager.AppSettings.Get("defaultPhotoFolder").Trim(); }
            set
            {
                ConfigurationManager.AppSettings["defaultPhotoFolder"] = value;

            }
        }


        #endregion

        #region dispose method

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #endregion

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel2 = new System.Windows.Forms.Panel();
            this.btnBrowse = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.btnStop = new System.Windows.Forms.Button();
            this.btnStart = new System.Windows.Forms.Button();
            this.panel3 = new System.Windows.Forms.Panel();
            this.txtLogger = new System.Windows.Forms.TextBox();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.button2 = new System.Windows.Forms.Button();
            this.panel2.SuspendLayout();
            this.panel3.SuspendLayout();
            this.SuspendLayout();
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.button2);
            this.panel2.Controls.Add(this.btnBrowse);
            this.panel2.Controls.Add(this.textBox1);
            this.panel2.Controls.Add(this.button1);
            this.panel2.Controls.Add(this.btnStop);
            this.panel2.Controls.Add(this.btnStart);
            this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel2.Location = new System.Drawing.Point(5, 5);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(816, 43);
            this.panel2.TabIndex = 1;
            // 
            // btnBrowse
            // 
            this.btnBrowse.Location = new System.Drawing.Point(448, 6);
            this.btnBrowse.Name = "btnBrowse";
            this.btnBrowse.Size = new System.Drawing.Size(53, 24);
            this.btnBrowse.TabIndex = 8;
            this.btnBrowse.Text = "Browse";
            this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(128, 9);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(314, 21);
            this.textBox1.TabIndex = 7;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(691, 7);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(90, 24);
            this.button1.TabIndex = 6;
            this.button1.Text = "Clear";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // btnStop
            // 
            this.btnStop.Enabled = false;
            this.btnStop.Location = new System.Drawing.Point(595, 6);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(90, 24);
            this.btnStop.TabIndex = 5;
            this.btnStop.Text = "Stop";
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(19, 9);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(90, 24);
            this.btnStart.TabIndex = 4;
            this.btnStart.Text = "Start Upload";
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // panel3
            // 
            this.panel3.Controls.Add(this.txtLogger);
            this.panel3.Controls.Add(this.panel2);
            this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel3.Location = new System.Drawing.Point(0, 0);
            this.panel3.Name = "panel3";
            this.panel3.Padding = new System.Windows.Forms.Padding(5);
            this.panel3.Size = new System.Drawing.Size(826, 518);
            this.panel3.TabIndex = 2;
            // 
            // txtLogger
            // 
            this.txtLogger.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtLogger.Location = new System.Drawing.Point(5, 48);
            this.txtLogger.Multiline = true;
            this.txtLogger.Name = "txtLogger";
            this.txtLogger.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogger.Size = new System.Drawing.Size(816, 465);
            this.txtLogger.TabIndex = 3;
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(513, 9);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(60, 20);
            this.button2.TabIndex = 9;
            this.button2.Text = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(826, 518);
            this.Controls.Add(this.panel3);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Upload SiteHosted Pictures";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.panel2.ResumeLayout(false);
            this.panel2.PerformLayout();
            this.panel3.ResumeLayout(false);
            this.panel3.PerformLayout();
            this.ResumeLayout(false);

        }
        #endregion

        #region logic flow

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            this.Closing += new CancelEventHandler(Form1_Closing);
        }

        /// <summary>
        /// while the form is closing, stop all threads to execute
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Closing(object sender, CancelEventArgs e)
        {
            btnStop_Click(sender, e);
        }

        private void btnStop_Click(object sender, System.EventArgs e)
        {
            if (fetcher == null)
                return;
            btnStop.Enabled = false;
            fetcher.Stop();
            fetcher = null;
            btnStart.Enabled = true;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {

            // folderBrowserDialog1.SelectedPath = this.textBox1.Text.Trim();
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyDocuments;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.textBox1.Text = folderBrowserDialog1.SelectedPath;
            }


        }

        private void btnStart_Click(object sender, System.EventArgs e)
        {
            string token = eBayToken;
            if (token.Length == 0)
            {
                MessageBox.Show("Please Fetch your eBay token firstly.");
                new FetchTokenForm().ShowDialog(this);
                return;
            }

            if (string.IsNullOrEmpty(this.textBox1.Text))
            {
                MessageBox.Show("Please choose or input your path.");
                return;
            }
            if (DefaultPhotoFolder != this.Text.Trim())
            {
                DefaultPhotoFolder = this.textBox1.Text.Trim();

                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["defaultPhotoFolder"].Value = DefaultPhotoFolder;
                config.Save(ConfigurationSaveMode.Modified);
            }


            Clear();
            LoadImages(this.textBox1.Text.Trim());
            if (listingImages.Count == 0)
            {
                MessageBox.Show("There are no valid images in this path .Please change a different path.");
                return;
            }
            if (fetcher != null)
                return;



            btnStart.Enabled = false;

            fetcher = new ItemFetcher(this, txtLogger, NumThreads, eBayUser, token, IsRampUp, listingImages);
            fetcher.FetchCompleteEvent += new GetItemTester.ItemFetcher.FetchCompleteDelegate(fetcher_FetchCompleteEvent);
            fetcher.UploadSiteHostePicturesCompleteEvent += new ItemFetcher.UploadSiteHostePicturesCompleteDelegate(fetcher_UploadSiteHostePicturesCompleteEvent);
            fetcher.Start();

            btnStop.Enabled = true;
        }

        void Clear()
        {
            this.txtLogger.Text = "";
            productCodes.Clear();
            listingImages.Clear();
            generatedListingImages.Clear();
        }
        void fetcher_UploadSiteHostePicturesCompleteEvent(object sender, UploadSitedHostedPicturesEventArgs e)
        {
            generatedListingImages[e.Item.Key].EPSUrl = e.Item.Value;
        }

        private void LoadImages(string listingImageFolder)
        {


            string[] files = Directory.GetFiles(listingImageFolder);
            foreach (string file in files)
            {
                string extension = Path.GetExtension(file);
                if (extension.ToUpper() == ".PNG" || extension.ToUpper() == ".JPG" || extension.ToUpper() == ".GIF" || extension.ToUpper() == ".JPEG")
                {
                    //*All of our codes begin with "MTSJ", then have 5 digits, then are separated by a dash and a number of the image -1 through -12
                    string fileName = Path.GetFileName(file).Replace(extension, "");
                    string productCode = fileName.Substring(0, 9);
                    if (!productCodes.Contains(productCode))
                    {
                        productCodes.Add(productCode);
                    }
                    KeyValuePair<string, string> dic = new KeyValuePair<string, string>(fileName, file);
                    listingImages.Add(dic);

                    ImageItem imageItem = new ImageItem();
                    imageItem.ProductCode = productCode;
                    generatedListingImages.Add(new KeyValuePair<string, ImageItem>(fileName, imageItem));
                }

            }
            string[] directories = System.IO.Directory.GetDirectories(listingImageFolder);
            foreach (string directory in directories)
            {
                LoadImages(directory);

            }
        }

        private void fetcher_FetchCompleteEvent(object sender, EventArgs e)
        {
            if (btnStop.InvokeRequired)
            {
                SetButtonCallBack d = new SetButtonCallBack(SetButtonEnabled);
                this.Invoke(d, new object[] { btnStop, false });
            }
            else
            {
                btnStop.Enabled = false;

            }

            fetcher = null;

            if (btnStart.InvokeRequired)
            {
                SetButtonCallBack d = new SetButtonCallBack(SetButtonEnabled);
                this.Invoke(d, new object[] { btnStart, true });
            }
            else
            {
                btnStart.Enabled = true;
            }
            //geneated images
            string fileName = Export();
            MessageBox.Show(string.Format("Export successfully,please open the path {0}!", fileName));
        }

        private delegate void SetButtonCallBack(Button button, bool enabled);

        private void SetButtonEnabled(Button button, bool enabled)
        {
            button.Enabled = enabled;
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            this.txtLogger.Text = "";



        }
        string Export()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Custom Label");
            dt.Columns.Add("EPS Url");

            foreach (string productCode in productCodes)
            {
                DataRow row = dt.NewRow();
                row.BeginEdit();
                row["Custom Label"] = productCode;
                string epsUrl = string.Empty;
                for (int i = 1; i <= 12; i++)
                {
                    string pictureName = string.Empty;
                    if (i == 1)
                    {
                        pictureName = productCode;
                        if (generatedListingImages.ContainsKey(pictureName))
                        {
                            epsUrl += generatedListingImages[pictureName].EPSUrl + "|";
                        }
                        else
                        {
                            pictureName = productCode + "-" + i;
                            if (generatedListingImages.ContainsKey(pictureName))
                            {
                                epsUrl += generatedListingImages[pictureName].EPSUrl + "|";
                            }
                        }
                    }
                    else
                    {
                        pictureName = productCode + "-" + i;
                        if (generatedListingImages.ContainsKey(pictureName))
                        {
                            epsUrl += generatedListingImages[pictureName].EPSUrl + "|";
                        }
                    }

                }
                if (!string.IsNullOrEmpty(epsUrl))
                {
                    epsUrl = epsUrl.TrimEnd(new char[] { '|' });
                }
                row["EPS Url"] = epsUrl;

                row.EndEdit();
                dt.Rows.Add(row);
            }


            string displayName = "ListingEPSUrl_Export_" + DateTime.Now.ToString("yyyy-MM-d-HHmmss") + ".xls";
            string fileName = Path.Combine(Application.StartupPath, displayName);
            Export(fileName, dt);

            return fileName;

        }

        public static void Export(string fileName, DataTable dt)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.Sheet sheet = book.CreateSheet("ListingEPSUrl");
            NPOI.SS.UserModel.Row row = sheet.CreateRow(0);


            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.Row row2 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                    row2.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
            }


            FileStream file = new FileStream(@fileName, FileMode.Create);
            book.Write(file);
            file.Close();
            book.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.DefaultPhotoFolder))
            {
                this.textBox1.Text = DefaultPhotoFolder;
            }
            if (String.IsNullOrEmpty(this.eBayToken))
            {
                new FetchTokenForm().ShowDialog(this);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            eBayApi.GetItem("290874241567", this.eBayToken);
            eBayApi.GetCategorySpecifics(eBayToken);
        }


    }
}
